package com.wskj.framework.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.wskj.common.utils.common.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TimeZone;

/**
 * jackson 配置
 *
 * @author Lion Li
 */
@Slf4j
@Configuration
public class JacksonConfig {

    @Bean
    public BeanPostProcessor objectMapperBeanPostProcessor() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (!(bean instanceof ObjectMapper)) {
                    return bean;
                }
                ObjectMapper objectMapper = (ObjectMapper) bean;
                // 全局配置序列化返回 JSON 处理
                SimpleModule simpleModule = new SimpleModule();
                // 出参序列化
                simpleModule.addSerializer(LocalDateTime.class, LocalDateTimeSerializer.INSTANCE);
                // 入参反序列化
                simpleModule.addDeserializer(LocalDateTime.class, LocalDateTimeDeserializer.INSTANCE);
                // long型统一转化为字符串(序列化)
                simpleModule.addSerializer(Long.class, new ToStringSerializer());
                objectMapper.registerModule(simpleModule);
                objectMapper.setTimeZone(TimeZone.getDefault());
                // 处理空指针时设置的值
                objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
                    @Override
                    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                        String fieldName = gen.getOutputContext().getCurrentName();
                        try {
                            // 反射获取字段类型
                            Field field = gen.getCurrentValue().getClass().getDeclaredField(fieldName);
                            if (Objects.equals(field.getType(), String.class)) {
                                // 字符串型空值""
                                gen.writeString("");
                                return;
                            } else if (Objects.equals(field.getType(), List.class)) {
                                // 列表型空值返回[]
                                gen.writeStartArray();
                                gen.writeEndArray();
                                return;
                            } else if (Objects.equals(field.getType(), Map.class)) {
                                // map型空值返回{}
                                gen.writeStartObject();
                                gen.writeEndObject();
                                return;
                            } else if(Objects.equals(field.getType(),Integer.class)){
                                // 默认返回0
                                gen.writeNumber(0);
                                return;
                            } else if(Objects.equals(field.getType(), BigDecimal.class)){
                                gen.writeNumber(BigDecimal.ZERO);
                                return;
                            } else if(Objects.equals(field.getType(),Boolean.class)){
                                gen.writeBoolean(false);
                                return;
                            }
                        } catch (NoSuchFieldException e) {
                        }
                        // 默认返回null
                        gen.writeNull();
                    }
                });
                JsonUtils.init(objectMapper);
                log.info("初始化 jackson 配置");
                return bean;
            }
        };
    }

    /**
     * null字符转为""
     * @param builder
     * @Author gunk
     * @return
     */
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString(StringUtils.EMPTY);
            }
        });
        return objectMapper;
    }

}
